/* Copyright (c) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package openbang.account.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openbang.account.service.util.CacheHelper;
import openbang.account.service.vo.CacheKeyDefine;
import openbang.account.service.vo.UserLoginInfo;



/**
 * 清理Cache里过期的数据  --- Session数据
 * 
 * 调用者：cron.xml中配置   /cron/clearExpired
 * 
 * 必须注意：并发性
 * 
 * @author aibo zeng
 *
 */

@SuppressWarnings("serial")
public class CacheClearServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(CacheClearServlet.class.getName());

	private static final long UNLIVE_MAX_TIME = 1000*60*30;//30分钟
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	 		throws IOException, ServletException {
		doPost(req,resp);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException, ServletException {	
		//处理 session  _as_SESSION
		
/*		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("_ah_SESSION");
		PreparedQuery results = datastore.prepare(query);
		int cleared = 0;
		try {
			for (Entity session : results.asIterable()) {
				Long expires = (Long)session.getProperty("_expires");
				if(System.currentTimeMillis()-expires>UNLIVE_MAX_TIME){
					datastore.delete(session.getKey());
					cleared++;					
				}
			}
		} catch (Throwable e) {
			log.severe(e.getMessage());
		}
*/		
		
		HashSet<String> allSession =  CacheHelper.getSessionAll();
		if(allSession==null || allSession.isEmpty()){
			//没有数据
			return;
		}
		Collection<String> canRemoveKey = new HashSet<String>();
		Iterator<String> iter = allSession.iterator();
		while(iter.hasNext()){
				String sessionKey = iter.next();
				UserLoginInfo user = (UserLoginInfo)CacheHelper.get(sessionKey);
				if(user==null){
					//allSession.remove(sessionKey);
					canRemoveKey.add(sessionKey);
				}
				else if(((new Date()).getTime() -user.getLastAccessDate().getTime()>UNLIVE_MAX_TIME)){
					canRemoveKey.add(sessionKey);
					//allSession.remove(sessionKey);
				}
				else{
				}
		}
		if(!canRemoveKey.isEmpty()){
			//CacheHelper.updSessionAll(allSession);
			//CacheHelper.removeAll(canRemoveKey, 0);
			allSession.removeAll(canRemoveKey);
    		CacheHelper.put(CacheKeyDefine.SESSION_ALL,allSession);
		}
		
		log.warning("come in CacheClearServlet() remove session key size="+canRemoveKey.size());
		
		//处理聊天群和消息 -- 见：OpenBangChat工程
		
    }
	
	public static void main(String[] args){
		//测试遍历过程中,对“元素”删除的影响
		List<String>  testList = new ArrayList<String>();
		testList.add("U1");
		testList.add("U23");
		testList.add("U3");
		testList.add("U4");
		testList.add("U53");
		testList.add("U6");
		testList.add("U7");
		
		Iterator<String> itera = testList.iterator();
		int i = 0 ;
		while(itera.hasNext()){
			System.out.println("i="+i);
			String str = itera.next();//中途不能有删除
			if(str.indexOf("3")>=0){
				testList.remove(str);
			}
			i++;
		}
/*
 * 		i=0
		i=0
		i=0
		Exception in thread "main" java.util.ConcurrentModificationException
			at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
			at java.util.AbstractList$Itr.next(AbstractList.java:343)
			at openbang.account.service.impl.CacheClearServlet.main(CacheClearServlet.java:98)
*/		
	}
	
}
